<template>
  <div id="media" v-if="loadState" :style="containerStyle" @dblclick="loadMedia">
    <video class="media_file" :ref="`media_file_${ID}`" v-if="FilePath" :controls="isShowToolBar" :muted="isPlayVolume"
           :autoplay="isAutoPlay" @play="videoConfigChange" @pause="videoConfigChange" @timeupdate="videoConfigChange"
           webkit-playsinline playsinline>
      <source :src="getFilePath(FilePath,'MEDIA')" type="video/mp4">
    </video>
    <img v-else class="open_file" title="打开" src="~@/assets/img/SlideEditor/media_icon.png" draggable="false"
         @click="loadMedia">
  </div>
  <img class="loading" v-else src="~@/assets/img/SlideEditor/Navigation/loading.gif" draggable="false">
</template>
<script>
  import {mapActions, mapGetters} from 'vuex'
  import action from '../../common/typeActions'
  import ipcs from '../../common/typeIpcs'
  import path from 'path'
  import uuid from 'uuid/v4'

  let remote = ''
  let fsextra = ''

  export default {
    name: 'Media',
    props: {
      ID: {type: String},
      FilePath: {type: String},
      FileCode: {type: String},
      isShowToolBar: {type: Boolean, default: false},
      isPlayVolume: {type: Boolean, default: false},
      isAutoPlay: {type: Boolean, default: false},
      containerStyle: {type: Object},
      isPlayFile: {type: Boolean, default: false},
      isReadonly: {type: Boolean, default: false}
    },
    data: function () {
      return {
        loadState: true
      }
    },
    watch: {
      isPlayFile: function (n, o) {
        let media = this.$refs[`media_file_${this.ID}`]
        if (!media) return
        if (n) {
          media.play()
        } else {
          media.pause()
        }
      },
      FilePath: function (n, o) {
        if (o && n && n !== o) {
          this.$nextTick(() => {
            let media = this.$refs[`media_file_${this.ID}`]
            if (media) media.load()
          })
        }
      }
    },
    computed: {
      ...mapGetters(['getFilePath', 'caseFolder'])
    },
    mounted: function () {
      let self = this
      if (!self.isShowToolBar && !process.browser) {
        self.$electron.ipcRenderer.on(
          ipcs.RENDERER.mediaStateSync,
          (event, arg) => {
            // 获取视频播放组件
            let video = self.$refs[`media_file_${arg.ID}`]
            if (!video) return
            video.currentTime = arg.time
            if (arg.paused) {
              video.pause()
            } else {
              video.play()
            }
          }
        )
      }
    },
    methods: {
      ...mapActions({
        addExternalFile: action.COMMON.AddExternalFile,
        setElementAttr: action.SLIDEEDITOR.SetElementAttr
      }),
      // 上传视频文件
      loadMedia: function () {
        let self = this
        if (self.isReadonly) return
        if (remote) {
          let extensions = {
            properties: ['openFile', 'showHiddenFiles'],
            filters: [{name: 'Media', extensions: ['mp4']}]
          }
          remote.dialog.showOpenDialog(
            remote.getCurrentWindow(),
            extensions,
            async rs => {
              try {
                if (!rs) return
                self.loadState = false
                let {ext} = path.parse(rs[0])
                let toPath = path.join(this.caseFolder(), uuid() + ext)
                // 移动文件到案件文件夹下
                fsextra.copySync(rs[0], toPath)
                await this.addExternalFile({
                  id: self.ID,
                  fileID: self.FileCode,
                  imageID: self.FilePath,
                  path: toPath
                })

                self.loadState = true
                // self.$emit("MediaLoadFinish", self.ID);
              } catch (error) {
                self.$alert(error.message, '提示', {type: 'warning'})
              }
            }
          )
        } else {
          let input = document.createElement('input')
          input.type = 'file'
          input.multiple = false
          input.accept = 'audio/mp4, video/mp4'
          input.onchange = async () => {
            if (event.target.files.length > 0) {
              this.loadState = false
              if (!/mp4/i.test(path.extname(event.target.files[0].name))) return this.$message('请选择MP4格式的视频文件')
              let formData = new FormData()
              formData.append('dbPath', this.$store.state.appearCourt.casePath)
              for (let i = 0; i < event.target.files.length; i++) {
                formData.append('files', event.target.files[i])
              }
              let uploadFiles = await this.$api.post.uploadFiles(formData)
              await this.addExternalFile({
                id: this.ID,
                fileID: this.FileCode,
                imageID: this.FilePath,
                file: uploadFiles[0]
              })
              // this.$emit('MediaLoadFinish', {ID: this.ID, Path: uploadFiles[0].FilePath})
              this.loadState = true
            }
          }
          input.click()

          // let extensions = {
          //   accept: 'audio/mp4, video/mp4',
          //   multiple: false
          // }
          // this.openFileDialog(extensions, async () => {
          //   if (event.target.files.length > 0) {
          //     if (!/mp4/i.test(path.extname(event.target.files[0].name))) return this.$message('请选择MP4格式的视频文件')
          //     try {
          //       /* eslint-disable new-cap */
          //       let uploadFileBySlice = new this.$methods.uploadFileBySlice({
          //         file: event.target.files[0],
          //         fileType: 'caseAccessory'
          //       })
          //       uploadFileBySlice.eventBus.on('success', async data => {
          //         await this.addExternalFile({
          //           id: this.ID,
          //           fileID: this.FileCode,
          //           imageID: this.FilePath,
          //           path: { Files: [data] }
          //         })
          //         // this.$emit("MediaLoadFinish", {ID: this.ID, Path: result.FilePath});
          //         this.loadState = true
          //       })
          //       uploadFileBySlice.eventBus.on('fail', err => {
          //         this.$alert(err.message, '错误', { type: 'error' })
          //         this.loadState = true
          //       })
          //       this.loadState = false
          //       uploadFileBySlice.start()
          //     } catch (error) {
          //       this.$alert(error.message, '提示')
          //     }
          //   }
          // })
        }
      },
      videoConfigChange: function () {
        if (!this.isShowToolBar || process.browser) return
        // 获取视频播放组件
        let video = this.$refs[`media_file_${this.ID}`]
        if (!video) return
        // 向扩展进程发送消息
        this.$electron.ipcRenderer.send(ipcs.MAIN.mediaStateSync, {
          ID: this.ID,
          time: video.currentTime,
          paused: video.paused
        })
      }
    }
  }
</script>
<style>
  #media {
    width: 100%;
    height: 100%;
  }

  #media source {
    width: 100%;
    height: 100%;
  }

  #media .media_file {
    width: 100%;
    height: 100%;
    object-fit: fill;
  }

  #media .open_file {
    position: absolute;
    top: calc(50% - 16px);
    left: calc(50% - 16px);
    cursor: pointer;
  }

  .loading {
    width: 100%;
    height: 100%;
  }
</style>
